package com.boot.project.admin.aop;

import com.boot.project.core.model.result.ProfileResult;
import com.boot.project.core.util.RequestUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

/**
 * 向request中放入username
 */
@Slf4j
@Aspect
@Component
@Order(999)
public class SetUsernameAop {

    @Pointcut(value = "execution(* com.boot.project.admin.controller.*.*.*(..))")
    public void pointcut() {
    }

    @Around("pointcut()")
    public Object setUsername(ProceedingJoinPoint point) throws Throwable {
        // 每次访问controller前，先去安全数据中拿username放到request里
        HttpServletRequest request = RequestUtils.getRequest();
        if (request != null) {
            ProfileResult result = (ProfileResult) SecurityUtils.getSubject().getPrincipal();
            if (result != null) {
                request.setAttribute("username", result.getUsername());
            }
        }
        return point.proceed();
    }
}
